import Foundation
import Network

// 连接设置模型，专注于TCP连接
class ConnectionSettings: ObservableObject {
    @Published var ipAddress: String {
        didSet {
            UserDefaults.standard.set(ipAddress, forKey: "ipAddress")
        }
    }
    
    @Published var port: String {
        didSet {
            UserDefaults.standard.set(port, forKey: "port")
        }
    }
    
    @Published var cameraPort: String {
        didSet {
            UserDefaults.standard.set(cameraPort, forKey: "cameraPort")
        }
    }
    
    // 是否已连接成功
    @Published var isConnected: Bool = false
    
    // 是否正在连接中
    @Published var isConnecting: Bool = false
    
    // 连接错误信息
    @Published var connectionError: String? = nil
    
    // TCP连接对象
    private var tcpConnection: NWConnection?
    
    init() {
        // 从UserDefaults加载保存的值，或使用默认值
        self.ipAddress = UserDefaults.standard.string(forKey: "ipAddress") ?? "192.168.1.11"
        self.port = UserDefaults.standard.string(forKey: "port") ?? "6000"
        self.cameraPort = UserDefaults.standard.string(forKey: "cameraPort") ?? "6500"
    }
    
    // 通过TCP连接到小车
    func connectTCP(completion: @escaping (Bool) -> Void) {
        // 重置状态
        isConnecting = true
        connectionError = nil
        
        // 验证IP地址和端口格式
        guard isValidIPAddress(ipAddress) else {
            connectionError = "IP地址格式不正确"
            isConnecting = false
            completion(false)
            return
        }
        
        guard let portNum = UInt16(port), portNum > 0 && portNum <= 65535 else {
            connectionError = "端口号格式不正确，请输入1-65535之间的数字"
            isConnecting = false
            completion(false)
            return
        }
        
        // 建立TCP连接
        let host = NWEndpoint.Host(ipAddress)
        let port = NWEndpoint.Port(rawValue: portNum)!
        let tcpOptions = NWProtocolTCP.Options()
        tcpOptions.connectionTimeout = 10 // 5秒超时
        
        let parameters = NWParameters(tls: nil, tcp: tcpOptions)
        // 设置允许复用本地端点
        parameters.allowLocalEndpointReuse = true
        
        // 创建连接
        tcpConnection = NWConnection(host: host, port: port, using: parameters)
        
        // 监听状态变化
        tcpConnection?.stateUpdateHandler = { [weak self] state in
            guard let self = self else { return }
            
            switch state {
            case .ready:
                print("TCP连接已就绪：\(self.ipAddress):\(self.port)")
                self.isConnected = true
                self.isConnecting = false
                completion(true)
                
            case .failed(let error):
                print("TCP连接失败：\(error)")
                self.connectionError = "连接失败：\(error)"
                self.isConnected = false
                self.isConnecting = false
                self.closeTCPConnection()
                completion(false)
                
            case .cancelled:
                print("TCP连接已取消")
                self.isConnected = false
                self.isConnecting = false
                completion(false)
                
            case .preparing:
                print("TCP连接准备中...")
                
            case .waiting(let error):
                print("TCP连接等待：\(error)")
                
            default:
                break
            }
        }
        
        // 启动连接
        tcpConnection?.start(queue: .main)
        
        // 设置超时
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            if self?.isConnecting == true {
                self?.connectionError = "连接超时，请检查小车是否开启或网络是否正常"
                self?.isConnected = false
                self?.isConnecting = false
                self?.closeTCPConnection()
                completion(false)
            }
        }
    }
    
    // 关闭TCP连接
    func closeTCPConnection() {
        tcpConnection?.cancel()
        tcpConnection = nil
        isConnected = false
    }
    
    // 发送TCP数据
    func sendData(_ data: Data, completion: @escaping (Bool) -> Void) {
        guard isConnected, let connection = tcpConnection else {
            completion(false)
            return
        }
        
        connection.send(content: data, completion: .contentProcessed { error in
            if let error = error {
                print("发送数据失败：\(error)")
                completion(false)
            } else {
                completion(true)
            }
        })
    }
    
    // 接收TCP数据
    func receiveData(completion: @escaping (Data?) -> Void) {
        guard isConnected, let connection = tcpConnection else {
            completion(nil)
            return
        }
        
        connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { data, _, isComplete, error in
            if let data = data, !data.isEmpty {
                completion(data)
            } else {
                completion(nil)
            }
            
            // 继续接收数据
            if !isComplete && error == nil {
                self.receiveData(completion: completion)
            }
        }
    }
    
    // 验证IP地址格式
    private func isValidIPAddress(_ ip: String) -> Bool {
        let parts = ip.split(separator: ".")
        guard parts.count == 4 else { return false }
        
        for part in parts {
            guard let num = Int(part), num >= 0 && num <= 255 else {
                return false
            }
        }
        return true
    }
} 
